import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import {useAuthStore} from "@/stores/auth.ts";

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginView.vue'),
      async beforeEnter(to, from, next) {
        const authStore = useAuthStore()
        const isLoggedIn: boolean = await authStore.isLoggedIn(); // 使用 await 等待异步函数返回结果

        if (isLoggedIn) {
          next({name: 'home'})
        } else {
          next()
        }
      }
    },
    {
      path: '/',
      name: 'home',
      component: HomeView,
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/about',
      name: 'about',
      component: () => import('../views/AboutView.vue'),
    },
    {
      path: '/forbidden',
      name: 'forbidden',
      component: () => import('../views/ForbiddenView.vue'),
    },
    {
      path: '/:pathMatch(.*)*', // 通配符路由
      name: 'not-found',
      component: () => import('../views/NotFoundView.vue'),
    }
  ]
})

router.beforeEach(async (to, from, next) => {
  console.log('beforeEach from', from)
  console.log('beforeEach to', to)
  const authStore = useAuthStore()
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)

  const isLoggedIn: boolean = await authStore.isLoggedIn();
  if (requiresAuth && !isLoggedIn) {
    next({ name: 'login' })
  } else {
    next()
  }
})

export default router
